import java.util.StringTokenizer;
import ij.ImagePlus;
import ij.Macro;
import ij.plugin.filter.PlugInFilter;
import ij.process.ImageProcessor;

public class Clip_ implements PlugInFilter {


	private String args;

	@Override
	public void run(ImageProcessor ip) {
		
		args = Macro.getOptions();
		float lower = 117, higher = 184, lowerValue = 0, higherValue = 255;
		if (args!=null) {
			StringTokenizer tokenizer = new StringTokenizer(args);
			lower = Float.parseFloat(tokenizer.nextToken());
			higher = Float.parseFloat(tokenizer.nextToken());
			lowerValue = Float.parseFloat(tokenizer.nextToken());
			higherValue = Float.parseFloat(tokenizer.nextToken());
		}
		if (ip.getPixels() instanceof byte[]) {
			byte[] pixels = (byte[]) ip.getPixels();
			for (int i = 0; i < pixels.length; i++) {
				int pix = pixels[i] & 0xff;
				if (pix < lower)
					pixels[i] = (byte) lowerValue;
				if (pix > higher)
					pixels[i] = (byte) higherValue;
			}
		} else if (ip.getPixels() instanceof short[]) {
			short[] pixels = (short[]) ip.getPixels();
			for (int i = 0; i < pixels.length; i++) {
				int pix = pixels[i] & 0xffff;
				if (pix < lower)
					pixels[i] = (short) lowerValue;
				if (pix > higher)
					pixels[i] = (short) higherValue;
			}
		} else if (ip.getPixels() instanceof float[]) {
			float[] pixels = (float[]) ip.getPixels();
			for (int i = 0; i < pixels.length; i++) {
				float j = pixels[i];
				if (j < lower)
					pixels[i] = lowerValue;
				if (j > higher)
					pixels[i] = higherValue;
			}
		}


	}

	@Override
	public int setup(String arg, ImagePlus imp) {
		return DOES_16 + DOES_32 + DOES_8G;
	}
}
